import axios from 'axios'
import config from './config'
import store from '@/store'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message, MessageBox } from 'element-ui'
import router from '@/router'

export default function $axios(options) {
  return createAxios(options, config.baseUrl)
}

export const axiosCD = (options) => {
  //console.log("config.cdBaseUrl", config, process.env.BaseConfig.cdBaseUrl)
  return createAxios(options, process.env.BaseConfig.testUrl)
}
//环卫的ip
export const axiosHw = (options) => {
  //console.log("config.cdBaseUrl", config, process.env.BaseConfig.cdBaseUrl)
  return createAxios(options, config.huanWeiUrl)
}
// 是否显示重新登录
export let isRelogin = { show: false }

export const createAxios = (options, baseUrl) => {
  return new Promise((resolve, reject) => {
    //获取token
    const instance = axios.create({
      baseURL: baseUrl || config.baseUrl,
      headers: config.headers,
      timeout: config.timeout,
      withCredentials: config.withCredentials
    })
    // request 请求拦截器
    instance.interceptors.request.use(
      (config) => {
        config.headers['token'] = getToken() //token在拦截器中增加
        return config
      },
      (error) => {
        // 1. 判断请求超时
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
          Message.error('timeout请求超时')
        }
        return Promise.reject(error) // 在调用的那边可以拿到(catch)你想返回的错误信息
      }
    )
    // response 响应拦截器
    instance.interceptors.response.use(
      (res) => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 0
        const data = res.data
        //token过期处理
        if (data.msg && data.msg.indexOf('过期') > -1) {
          if (!isRelogin.show) {
            isRelogin.show = true
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                isRelogin.show = false
                store.dispatch('user/resetToken').then(() => {
                  router.push({ path: '/login' }).catch(() => {})
                })
              })
              .catch(() => {
                isRelogin.show = false
              })
          }
        } else {
          if (code != 0) {
            Message.error(data.msg)
          }
        }
        return data
      },
      (err) => {
        if (err && err.response) {
          switch (err.response.status) {
            case 400:
              err.message = '请求错误'
              break
            case 401:
              err.message = '未授权，请登录'
              break
            case 403:
              err.message = '拒绝访问'
              break
            case 404:
              err.message = `请求地址出错: ${err.response.config.url}`
              break
            case 408:
              err.message = '请求超时'
              break
            case 500:
              err.message = '服务器内部错误'
              break
            case 501:
              err.message = '服务未实现'
              break
            case 502:
              err.message = '网关错误'
              break
            case 503:
              err.message = '服务不可用'
              break
            case 504:
              err.message = '网关超时'
              break
            case 505:
              err.message = 'HTTP版本不受支持'
              break
            default:
          }
          return Promise.reject(err) // 返回接口返回的错误信息
        } else {
          Message.error('系统错误！')
          return err
        }
      }
    )
    // 请求处理
    instance(options)
      .then((res) => {
        resolve(res)
        return false
      })
      .catch((error) => {
        reject(error)
      })
      .finally(function () {})
  })
}
